package rentadomus


class UploadImageController {

    int isd
    def index(){
        redirect(action: "main")
    }
    
    def main(Long id) {
        if(id!=null){
            isd = id
            def placeInstance = Place.get(id) 
            def Images = placeInstance.img.findAll();
            
            [placeInstance: placeInstance, Images : Images]  
            
            //return
        }
        else{
            flash.message = 'You need to specify a place!'
        }
          

    }
    def upload(Long id){
        def placeInstance = Place.get(id) 
        def f = request.getFile('uploadFile')
        if (f.empty) {
            flash.message = 'file cannot be empty'
            redirect(action: 'main',id:id)           
            return
        }
        def img = new Images(params)
        img.save(flush: true)
        placeInstance.addToImg(img)
        
        placeInstance.save(flush: true)
        println (placeInstance.mainImage )
        if (placeInstance.mainImage == 0 ){
            println 'updated'
            placeInstance.mainImage = img.id
            /*def Images = placeInstance.img.findAll();
            Images.each(){obj ->
                 if(obj.equals(img)){                    
                    println obj.
                }                
            }*/
            
        }        
        placeInstance.save(flush: true)
        redirect(action: 'main', id:id)        
    }
    
    def displayImage (){
        print 'los params'
        print params
        def img = Images.get(params.id)
        response.outputStream << img.uploadFile
    }    
    def deleteImage (){
        println params
        def placeInstance = Place.get(params.place)
        def img = Images.get(params.id)
        placeInstance.removeFromImg(img)
        println (placeInstance.mainImage )
        println (params.id )
        if (placeInstance.mainImage == params.id.toInteger()){
            if (placeInstance.img.findAll().isEmpty()){
                placeInstance.mainImage = 0
            }            
            else{
                placeInstance.mainImage = placeInstance.img.findAll().first().id
            } 
        }        
        placeInstance.save(flush: true)
        redirect(action: 'main', id:params.place)            
    }    
    
    def done(){
        println params
        def placeInstance = Place.get(params.id) 
        placeInstance.date = new Date()
        render(view: "/index")
    }
}
